<template>
  <el-dialog :model-value="dialogVisible" title="导出数据" width="35%" align-center @closed="handleCancel">
    <div class="dialog">
      <el-radio-group v-model="state.scope" style="display: block">
        <el-radio :label="1" style="display: block">仅导出当前页数据</el-radio>
        <el-radio :label="2" style="display: block">导出更多页数据</el-radio>
      </el-radio-group>
      <div :class="`page ${state.scope === 1 ? 'disabled' : ''}`">
        <label>页码范围:</label>
        <el-input-number
          v-model="state.start"
          :disabled="state.scope === 1"
          :min="1"
          :max="state.end"
          size="small"
          controls-position="right"
          style="width: 120px"
        />
        <span>到</span>
        <el-input-number
          v-model="state.end"
          :disabled="state.scope === 1"
          :min="state.start"
          :max="maxPage"
          size="small"
          controls-position="right"
          style="width: 120px"
        />
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">关闭</el-button>
        <el-button type="primary" @click="handleDownload">导出</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { withDefaults, computed, reactive } from 'vue'
import { ElDialog, ElRadioGroup, ElRadio, ElInputNumber } from 'element-plus'
import { export2Excel } from '@/utils'
import type { Column } from './types'

const emits = defineEmits(['update:visible', 'export'])

const props = withDefaults(
  defineProps<{
    visible: boolean
    cols: Column[]
    rows: any
    selection: boolean
    pageData: any[]
    excelName: string
    total: number
    pageSize: number
  }>(),
  {
    visible: false,
    cols: () => [] as Column[],
    rows: undefined,
    selection: true,
    pageData: () => [] as any[],
    excelName: '',
    total: 1,
    pageSize: 1
  }
)

const dialogVisible = computed(() => props.visible)

const maxPage = computed(() => Math.ceil(props.total / props.pageSize))

const state = reactive({ scope: 1, start: 1, end: 10 })

const handleCancel = () => {
  emits('update:visible', false)
}
const handleDownload = () => {
  if (state.scope === 1) {
    downloadLocal(props.cols, props.rows, props.selection, props.pageData, props.excelName)
  } else {
    downloadRemote()
  }
}
const downloadLocal = (_cols: Column[], _rows: any, _selection: boolean, _pageData: any[], _excelName: string) => {
  const cols = _cols.filter(col => col.isShow)
  const dataList: any[] = []
  if (_rows) {
    for (let r = 0; r < _rows.length; r++) {
      const tds = _rows[r].children
      const data: any[] = []
      for (let i = _selection ? 1 : 0; i < tds.length; i++) {
        const col = cols[_selection ? i - 1 : i]
        if (col.isExport) {
          if (col.exportFn) {
            data.push(col.exportFn(_pageData[r][col.prop], _pageData[r]))
          } else {
            data.push(tds[i].innerText)
          }
        }
      }
      dataList.push(data)
    }
  }
  export2Excel(
    cols.filter(col => col.isExport),
    dataList,
    _excelName ? _excelName : '导出数据'
  )
  emits('update:visible', false)
}
const downloadRemote = () => {
  const format: any = {} as any
  props.cols.forEach((c: Column) => {
    if (c.exportFormat || c.filters) {
      format[c.prop] = c.exportFormat ? c.exportFormat : c.filters
    }
  })
  emits('export', {
    start: state.start,
    end: state.end,
    name: `${props.excelName}.xlsx`,
    format: JSON.stringify(format),
    fields: JSON.stringify(
      props.cols
        .filter(col => col.isExport)
        .map(c => {
          return {
            field: c.prop,
            name: c.label
          }
        })
    )
  })
  emits('update:visible', false)
}

defineExpose({ downloadLocal })
</script>

<style lang="scss" scoped>
.dialog {
  padding-left: 4rem;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.page {
  display: flex;
  align-items: center;
  padding-left: 22px;
  & > * {
    margin-right: 10px;
  }
  &.disabled {
    color: $--color-text-secondary;
  }
}
</style>
